//
//  JXMallViewController.m
//

#import "JXMallViewController.h"

#import "JXItemDetailViewController.h"
#import "JXMallHeaderCell.h"
#import "JXMallTableViewCell.h"

#import "JXMCSUserManager.h"
#import "JXLocalPushManager.h"
#import "JXMcsChatViewController.h"

@interface JXMallViewController ()<UITableViewDataSource, UITableViewDelegate, JXClientDelegate>

@property(nonatomic, strong) NSArray *datasource;
@property(nonatomic, strong) UITableView *mallTableView;
@property(nonatomic, strong) UIButton *unreadMessageBtn;
@property(nonatomic, assign) NSInteger unreadCount;

@end

@implementation JXMallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self mallTableView];

    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    UIButton *getCSBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [getCSBtn setFrame:CGRectMake(0, 0, 44, 44)];
    [getCSBtn addTarget:self action:@selector(clickGetCSBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:getCSBtn];

    UIButton *unreadMessageBtn = [[UIButton alloc] init];
    [unreadMessageBtn setBackgroundImage:JXChatImage(@"corner_uiclick") forState:UIControlStateNormal];
    [unreadMessageBtn setBackgroundColor:JXColorWithRGB(38, 165, 239)];
    [unreadMessageBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    unreadMessageBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [unreadMessageBtn setTitle:@"1" forState:UIControlStateNormal];
    unreadMessageBtn.frame = CGRectMake(37, 4, 16, 16);
    unreadMessageBtn.layer.cornerRadius = 8;
    unreadMessageBtn.layer.masksToBounds = YES;
    unreadMessageBtn.hidden = YES;
    unreadMessageBtn.userInteractionEnabled = NO;
    [rightView addSubview:unreadMessageBtn];
    self.unreadMessageBtn = unreadMessageBtn;

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    [self.navigationItem setRightBarButtonItem:rightItem];
    [self.navigationItem setTitle:nil];



    [sClient.mcsManager addDelegate:self];
    [sClient.chatManager addDelegate:self];
    [kDefaultNotificationCenter addObserver:self
                                    selector:@selector(updateTableHeadView:)
                                        name:kNotification_disConnected
                                      object:nil];
    [kDefaultNotificationCenter addObserver:self
                                    selector:@selector(networkConnected:)
                                        name:kNotification_loginSucess
                                      object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.mallTableView.height = selfViewHeight - sTabBarHeight;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:JXGetSuitableImage(@"mainNav")
                                                  forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:JXImage(@"basicNav")
                                                  forBarMetrics:UIBarMetricsDefault];
}

- (void)clickGetCSBtn {
    self.unreadCount = 0;
    [[JXMCSUserManager sharedInstance] requestCSForUI:self.navigationController indexPath:0];
}

#pragma mark 私有方法

- (UITableView *)mallTableView {
    if (!_mallTableView) {
        _mallTableView =
                [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        _mallTableView.dataSource = self;
        _mallTableView.delegate = self;
        [self.view addSubview:_mallTableView];
    }
    return _mallTableView;
}

- (void)networkConnected:(NSNotification *)notification {
    if (self.mallTableView.tableHeaderView) {
        self.mallTableView.tableHeaderView = nil;
    }
}

- (void)updateTableHeadView:(NSNotification *)notification {
    if (!self.mallTableView.tableHeaderView) {
        UIView *headView =
                [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        headView.backgroundColor = [UIColor yellowColor];
        headView.alpha = 0.3;
        UILabel *textLabel = [[UILabel alloc] initWithFrame:headView.bounds];
        textLabel.textAlignment = NSTextAlignmentCenter;
        textLabel.font = [UIFont systemFontOfSize:15];
        textLabel.textColor = [UIColor blackColor];
        textLabel.text = @"连接已断开";
        textLabel.layer.borderColor = [UIColor clearColor].CGColor;
        textLabel.layer.borderWidth = 1.f;
        [headView addSubview:textLabel];
        self.mallTableView.tableHeaderView = headView;
    }
}

- (NSArray *)datasource {
    if (_datasource.count < 1) {
        UIImage *headerImage = JXGetSuitableImage(@"mainHeader");
        UIImage *goodImage1 = JXGetSuitableImage(@"mainFirstGood");
        UIImage *goodImage2 = JXGetSuitableImage(@"mainSecondGood");
        UIImage *goodImage3 = JXGetSuitableImage(@"mainThirdGood");
        _datasource = @[ headerImage, goodImage1, goodImage2, goodImage3 ];
    }
    return _datasource;
}

- (CGFloat)getGoodInfoCellHeight {
    CGFloat height = 100;
    iPhoneType type = [UIDevice getCurrentIPhoneType];
    switch (type) {
        case iPhone4:
        case iPhone5:
            height = 196;
            break;
        case iPhone6:
            height = 230;
            break;
        case iPhone6Plus:
            height = 252;
            break;
        default:
            break;
    }
    return height;
}

- (CGFloat)getHeaderCellHeight {
    CGFloat height = 66;
    iPhoneType type = [UIDevice getCurrentIPhoneType];
    switch (type) {
        case iPhone4:
        case iPhone5:
            height = 66;
            break;
        case iPhone6:
            height = 104;
            break;
        case iPhone6Plus:
            height = 114;
            break;
        default:
            break;
    }
    return height;
}

- (void)setUnreadCount:(NSInteger)unreadCount {
    _unreadCount = unreadCount;
    if (unreadCount == 0) {
    [self.unreadMessageBtn setTitle:@"" forState:UIControlStateNormal];
    self.unreadMessageBtn.hidden = YES;
    }
}

#pragma mark 监听回呼

- (void)didServiceRecall:(JXWorkgroup *)workgroup withError:(JXError *)error {
    if (!error) {
        [[JXLocalPushManager sharedInstance]
                scheduleLocalNotificationWithSession:workgroup.serviceID];
    } else {
        // TODO:回呼失败处理
    }
}

#pragma mark UITableViewDatasource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JXMallHeaderCell *cell =
            [[JXMallHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:nil
                                    backgroundImage:self.datasource[indexPath.section]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [self getHeaderCellHeight];
    } else {
        return [self getGoodInfoCellHeight];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0000001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!(indexPath.section == 0)) {
        JXItemDetailViewController *goodDetailVC = [[JXItemDetailViewController alloc] init];
        goodDetailVC.hidesBottomBarWhenPushed = YES;
        goodDetailVC.selectedIndexPath = indexPath.section;
        [JXLocalPushManager sharedInstance].indexPath = indexPath.section;
        [self.navigationController pushViewController:goodDetailVC animated:YES];
    }
}

#pragma mark- JXChatManagerDelegate
- (void)didReceiveMessage:(JXMessage *)message {
    if (![[self topViewController] isKindOfClass:[JXMcsChatViewController class]]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!message.isSender) {
                self.unreadCount++;
                self.unreadMessageBtn.hidden = NO;
                [self.unreadMessageBtn setTitle:[NSString stringWithFormat:@"%zd",self.unreadCount] forState:UIControlStateNormal];
            }
        });
    }
}

- (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

@end
